package CrowdCounting.Model;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public abstract class DisplayFrame extends JFrame {

    public File displayImage(JLabel imageLabel, String imagePath) {
        BufferedImage image = null;
        File imageFile = null;
        try {
            imageFile = readImage(imagePath);
            if (imageFile == null) return null;
            image = ImageIO.read(imageFile);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        imageLabel.setText("");
        imageToLable(imageLabel, image);
        return imageFile;
    }


    public File readImage(String imagePath) throws InterruptedException {
        int count = 0;
        File imageFile = new File(imagePath);
        while (!Util.fileExistenceCheck(imageFile) || !Util.checkImage(imageFile)) {
            count++;
            if (count == 100) return null;
            Thread.sleep(600);
            imageFile = new File(imagePath);
            System.out.println(imagePath + " 等待加载中...");
        }
        System.out.println(imagePath + "加载成功");
        return imageFile;
    }

    public void imageToLable(JLabel imageLabel, Image image) {
        ImageIcon imageIcon = new ImageIcon(image);
        imageLabel.setIcon(imageIcon);
        imageLabel.repaint();
        validate();
        repaint();
    }

    public void displayText(JLabel textLabel, String text) {
        textLabel.setText(text);
        textLabel.repaint();
        validate();
        repaint();
    }

}
